import CryptoJS from "crypto-js";
import store from "../store/index";
const add_password = false;
import router from "../router/index"; //导入引用router,添加访问页面出错
import { Toast } from "vant";
// import CryptoJS from 'crypto-js'
// const CryptoJS = require('crypto-js');
// import {encrypt} from "./AESUtils";
// import {encrypt}
const desKey = "app.data.user_password_key";
export default class GetNetUtil {


  /**
   * 普通的get请求
   * @param {*} url 地址
   * @param {*} params  参数
   * @param {*} callback  成功后的回调
   */
  static requestGet(url, params, callback) {
    let env = import.meta.env;
    let newUrl = '';
    if(env.VITE_APP_ENV === 'production'){
      newUrl = '/oliao/token';
    }else {
      newUrl = '/oliao'
    }
    newUrl = newUrl+ url
    //添加公共参数
    var newParams = this.getNewParams(params); //接口自身的规范，可以忽略
    console.log("get 请求参数",newParams)
    newUrl = newUrl + "?" + newParams;
    fetch(newUrl, {
      method: "GET",
      mode:'cors',
      headers: {
        'Content-Type': "application/octet-stream;charset=UTF-8",
      },
      responseType: 'blob'
      // body: newParams,
    }).then((res)=>{
      return res.blob();
    })
        .then((response) => {
          callback(response);
      }).then((text) => {
      }).then((json) => {
      }).catch((error) => {
        console.log(error);
        router.replace({
          path: "Error",
        });
      });
  }

  /**
   * post key-value 形式 hader为'Content-Type': 'application/x-www-form-urlencoded'
   * @param {*} url
   * @param {*} service
   * @param {*} params
   * @param {*} callback
   */
  static requestPost(url, service, params, callback) {
    let env = import.meta.env;
    console.log("VITE_APP_ENV",env.VITE_APP_ENV)
    let newUrl = '';
    if(env.VITE_APP_ENV === 'production'){
        newUrl = '/oliao/token';
    }else {
        newUrl = '/oliao'
    }
    newUrl = newUrl + url
    store.commit("setCover", true);
     let token = sessionStorage.getItem("token");
    console.log("newurl",newUrl);
    let body = this.AESEncrypt(JSON.stringify(params));
    // let body = JSON.stringify(params);

    //添加公共参数
    fetch(newUrl, {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
        // Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","Content-Type":"application/x-www-form-urlencoded;text/html;charset=UTF-8",
        token:token
      },
      body: body,
    })
      .then((response) => {
        if (response.status != 200) {
          store.commit("setCover", false);
          Toast("请求超时");
          router.replace({
            path: "Error",
          });
          return;
        }
        if (response.ok) {
          return response.text();
        }
      }).then((text) => {
        if (add_password) {
          return this.decryptByDESModeEBC(text);
        } else {
          return JSON.parse(text);
        }
      }).then((json) => {
        store.commit("setCover", false);
        if(json.resultCode === '200'){
          callback(json);
        }
       else if (json.resultCode === '2004') {
            router.replace({
              path: "Error",
            });
          Toast("toke过期，请重新登录！");
        }

        // else if (json.status === 1) {
        //   // router.replace({
        //   //     path: "Error"
        //   // })
        //   Toast(json.errDes);
        // } else {
        //   Toast(json.errDes);
        //   //   router.replace({
        //   //     path: "Error",
        //   //   });
        //   //   Toast("数据处理失败");
        // }
      }).catch((error) => {
        // router.replace({
        //     path: "Error"
        // })
        console.log(error);
        return;
      });
  }

  /**
   * 设置公共参数
   * @param {*} service  服务资源类型
   * @param {*} oldParams 参数 map
   * @return 新的参数
   */
  static getNewParams(params) {
    let newParams = "";
    if (add_password == false) {
      //未加密
      for (let key in params) {
        newParams = newParams + key + "=" + params[key] + "&";
      }
    } else {
      for (let key in params) {
        newParams = newParams + key + "=" + this.encryptByDES(params[key]) + "&";
      }
    }
    //去除字符换手动增加的一个&符号
    newParams = newParams.substring(0, newParams.length - 1);
    return newParams;
  }

  // DES加密
  static encryptByDES(message) {
    //模式为ECB padding为Pkcs7
    var encrypted = CryptoJS.TripleDES.encrypt(
      message,
      CryptoJS.enc.Utf8.parse(desKey),
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      }
    );
    //加密出来是一个16进制的字符串
    var value = encrypted.toString();
    value = encodeURIComponent(value);
    return value;
  }

  //des解密
  static decryptDes(message) {
    // message = message.replace(/\s%3D/g, "");
    var decrypted = CryptoJS.TripleDES.decrypt(
      message,
      CryptoJS.enc.Utf8.parse(desKey),
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      }
    );
    return decrypted.toString(CryptoJS.enc.Utf8);
  }

  //DES  ECB模式解密
  static decryptByDESModeEBC(ciphertext) {
    ciphertext = ciphertext.replace(/\s+/g, "");
    //把需要解密的数据从16进制字符串转换成字符byte数组
    var decrypted = CryptoJS.TripleDES.decrypt(
      ciphertext,
      CryptoJS.enc.Utf8.parse(desKey),
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      }
    );
    //以utf-8的形式输出解密过后内容
    var result_value = decrypted.toString(CryptoJS.enc.Utf8);
    var result_json = JSON.parse(result_value);
    return result_json;
  }


  static AESEncrypt (word) {
    const keyStr = 'wegongalknllalnf';
    const ivStr = keyStr;
    const key = CryptoJS.enc.Utf8.parse(keyStr);
    const iv = CryptoJS.enc.Utf8.parse(ivStr);
    const srcs = CryptoJS.enc.Utf8.parse(word);
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
    });
    return this.stringToHex(CryptoJS.enc.Base64.stringify(encrypted.ciphertext));
  }

  static stringToHex(str){
    var val="";
    for(var i = 0; i < str.length; i++){
      if(val == "")
        val = str.charCodeAt(i).toString(16);
      else
        val += "" + str.charCodeAt(i).toString(16);
    }
    return val;
  }
}
